package bookstore_mall.service.impl;

import bookstore_mall.domain.dto.user.LoginRequest;
import bookstore_mall.domain.dto.user.RegisterRequest;
import bookstore_mall.domain.dto.user.UserInfoResponse;
import bookstore_mall.mapper.UserMapper;
import bookstore_mall.service.UserService;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import bookstore_mall.domain.User;
import bookstore_mall.exception.BusinessException;
import bookstore_mall.resp.ResultCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 注册
     *
     * @param registerRequest 注册请求
     * @return 布尔值
     */
    @Override
    public Boolean register(RegisterRequest registerRequest) {
        // 校验手机号
        if (!StringUtils.hasText(registerRequest.getPhone())) {
            throw new BusinessException("手机号不能为空", ResultCodeEnum.PARAM_ERROR.getCode());
        }
        // 检查手机号是否已被使用
        LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
        phoneWrapper.eq(User::getPhone, registerRequest.getPhone());
        if (this.count(phoneWrapper) > 0) {
            throw new BusinessException("该手机号已被注册", ResultCodeEnum.DATA_DUPLICATION.getCode());
        }
        // 创建新用户
        User user = new User();
        user.setUser_id(UUID.randomUUID().toString());
        user.setPhone(registerRequest.getPhone());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        // 如果没有提供用户名，则使用手机号作为用户名
        user.setUsername(StringUtils.hasText(registerRequest.getUsername()) ?
                registerRequest.getUsername() : registerRequest.getPhone());
        user.setRole("user"); // 默认角色
        // 保存用户
        boolean saved = this.save(user);
        if (!saved) {
            throw new BusinessException(ResultCodeEnum.OPERATION_FAIL);
        }
        return true;
    }

    /**
     * 登录
     *
     * @param loginRequest 登录请求
     * @return 一串
     */
    @Override
    public String login(LoginRequest loginRequest) {
        // 校验手机号
        if (!StringUtils.hasText(loginRequest.getPhone())) {
            throw new BusinessException("手机号不能为空",ResultCodeEnum.PARAM_ERROR.getCode());
        }

        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, loginRequest.getPhone());
        User user = this.getOne(queryWrapper);

        // 验证用户是否存在
        if (user == null) {
            throw new BusinessException(ResultCodeEnum.USER_NOT_FOUND);
        }

        // 验证密码
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new BusinessException(ResultCodeEnum.PASSWORD_ERROR);
        }
        // 登录
        StpUtil.login(user.getUser_id());
        // 返回token
        return StpUtil.getTokenValue();
    }


    /**
     * 获取当前用户信息
     *
     * @return 用户信息响应
     */
    @Override
    public UserInfoResponse getCurrentUserInfo() {
        // 获取当前登录用户ID
        String userId = StpUtil.getLoginIdAsString();

        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUser_id, userId);
        User user = this.getOne(queryWrapper);

        if (user == null) {
            throw new BusinessException(ResultCodeEnum.USER_NOT_FOUND);
        }

        // 转换为响应对象
        UserInfoResponse response = new UserInfoResponse();
        BeanUtils.copyProperties(user, response);
        response.setUserId(user.getUser_id()); // 修正字段名
        return response;
    }

    /**
     * 注销
     */
    @Override
    public void logout() {
        StpUtil.logout();
    }
} 